package cn.finyzq.ss.games.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class HttpUtils {

    private static RestTemplate restTemplate = new RestTemplate();

    static{
        restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        restTemplate.getMessageConverters().add(new FastJsonHttpMessageConverter());
    }

    private static final String SINA_APPKEY = "3271760578";
    private static final String API_REQUEST_PREFIX = "/mini";
    private static final String APP_REQUEST_PREFIX = "/app";

    private HttpUtils(){}


    public static String getRemoteClientIp(HttpServletRequest request) {
        String[] ipHeaders = new String[]{"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        String ip = null;

        int index;
        for(index = 0; index < ipHeaders.length; ++index) {
            ip = request.getHeader(ipHeaders[index]);
            if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                break;
            }
        }

        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            index = ip.indexOf(44);
            if (index > 0) {
                String[] values = StringUtils.split(ip, ',');
                return values[0].trim();
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

    public static String getShortUrl(String longUrl){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        restTemplate.getMessageConverters().set(6, new FastJsonHttpMessageConverter());
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        String url = "http://mini.t.sina.com.cn/short_url/shorten.json?source=APPKEY&url_long=LONGURL".replace("APPKEY", SINA_APPKEY).replace("LONGURL", longUrl);
        JSONObject json = restTemplate.getForObject(url,JSONArray.class).getJSONObject(0);
        return json.getString("url_short");
    }

    public static boolean isApiRequest(HttpServletRequest request){
        String url = request.getRequestURI();
        return url.contains(API_REQUEST_PREFIX);
    }

    public static boolean isAppRequest(HttpServletRequest request){
        String url = request.getRequestURI();
        return url.contains(APP_REQUEST_PREFIX);
    }

    public static boolean isAjaxRequest(HttpServletRequest request){
        String header = request.getHeader("x-requested-with");
        return "XMLHttpRequest".equals(header);
    }

    public static RestTemplate getRestTemplate() {
        return restTemplate;
    }

    public static Map<String, String> getRequestParameterSingleMap(HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        if (map != null && map.size() > 0) {
            Map<String, String> resultMap = new LinkedHashMap(map.size());

            String paramName;
            String value;
            for(Enumeration en = request.getParameterNames(); en.hasMoreElements(); resultMap.put(paramName, value)) {
                paramName = (String)en.nextElement();
                value = request.getParameter(paramName);
            }

            return resultMap;
        } else {
            return new HashMap(0);
        }
    }




    public static String getQueryString(Map<String, String> param) {
        StringBuilder sb = new StringBuilder();
        for (String o : param.keySet()) {
            sb.append(o).append("=").append(param.get(o)).append("&");
        }
        String query = sb.toString();

        // 去除末尾&

        return query.substring(0, query.length() - 1);
    }



}
